home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
C & C++ Multimedia Cyber Classroom
/
C and C++ Multimedia Cyber Classroom (Prentice Hall) (1998).iso
/
src
/
fig12_04.jar
/
Ch12
/
Fig12_04
/
Tstack1.h
< prev
Wrap
C/C++ Source or Header
|
1997-10-30
|
2KB
|
56 lines
// Fig. 12.3: tstack1.h
// Class template Stack
#ifndef TSTACK1_H
#define TSTACK1_H
#include <iostream.h>
template< class T >
class Stack {
public:
Stack( int = 10 ); // default constructor (stack size 10)
~Stack() { delete [] stackPtr; } // destructor
bool push( const T& ); // push an element onto the stack
bool pop( T& ); // pop an element off the stack
private:
int size; // # of elements in the stack
int top; // location of the top element
T *stackPtr; // pointer to the stack
bool isEmpty() const { return top == -1; } // utility
bool isFull() const { return top == size - 1; } // functions
};
// Constructor with default size 10
template< class T >
Stack< T >::Stack( int s )
{
size = s > 0 ? s : 10;
top = -1; // Stack is initially empty
stackPtr = new T[ size ]; // allocate space for elements
}
// Push an element onto the stack
// return 1 if successful, 0 otherwise
template< class T >
bool Stack< T >::push( const T &pushValue )
{
if ( !isFull() ) {
stackPtr[ ++top ] = pushValue; // place item in Stack
return true; // push successful
}
return false; // push unsuccessful
}
// Pop an element off the stack
template< class T >
bool Stack< T >::pop( T &popValue )
{
if ( !isEmpty() ) {
popValue = stackPtr[ top-- ]; // remove item from Stack
return true; // pop successful
}
return false; // pop unsuccessful
}
#endif